package com.itmuch.box.controller.back.content;

import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.itmuch.box.core.base.BaseController;
import com.itmuch.box.domain.category.entity.Category;
import com.itmuch.box.domain.content.vo.ArticleAddVo;
import com.itmuch.box.domain.content.vo.ArticleEditVo;
import com.itmuch.box.domain.recomend.entity.Recomend;
import com.itmuch.box.domain.sort.entity.Sort;
import com.itmuch.box.domain.tag.entity.Tag;
import com.itmuch.box.service.category.CategoryService;
import com.itmuch.box.service.content.ContentArticleService;
import com.itmuch.box.service.content.ContentService;
import com.itmuch.box.service.recomend.RecomendService;
import com.itmuch.box.service.sort.SortService;
import com.itmuch.box.service.tag.TagService;
import com.itmuch.box.util.UrlUtil;

@Controller
@RequestMapping("${adminPath}/content")
public class BArticleController extends BaseController {
    @Resource
    private CategoryService categoryService;
    @Resource
    private SortService sortService;
    @Resource
    private ContentService contentService;
    @Resource
    private ContentArticleService contentArticleService;
    @Autowired
    private RecomendService recomendService;
    @Autowired
    private TagService tagService;
    @Autowired
    private UrlUtil urlUtil;

    /**
     * 插入文章(业务操作)
     * @param articleAddVo 文章vo
     * @param result jsr校验结果
     * @return 页面
     */
    @RequestMapping(value = "/add/{categoryId}", method = RequestMethod.POST)
    public String add(@PathVariable Integer categoryId, @Valid @ModelAttribute("articleAddVo") ArticleAddVo articleAddVo, BindingResult result,
            RedirectAttributes ra, HttpServletRequest req) {
        Category category = this.categoryService.findOne(categoryId);
        if (category != null) {
            Integer modelId = category.getModelId();
            if (modelId == 1) {
                if (!result.hasErrors()) {
                    Date issueTime = articleAddVo.getIssueTime() == null ? new Date() : articleAddVo.getIssueTime();
                    articleAddVo.setIssueTime(issueTime);

                    articleAddVo.setCategoryId(categoryId);

                    this.contentArticleService.insertArticle(articleAddVo);

                    // 成功
                    return UrlUtil.success(ra, "修改成功", this.urlUtil.urlRelativeToBack(req, "/content"));
                }
                // JSR校验不通过
                // 当前栏目信息
                articleAddVo.setCategoryId(categoryId);

                List<Recomend> recomends = this.recomendService.findAll();
                req.setAttribute("recomends", recomends);
                return "back/content/article/add";
            }
        }
        // TODO 栏目不存在, 或者不是文章页面, 跳转到错误页面提示
        return "";
    }

    /**
     * 编辑 页面
     * @param id 内容id
     * @return 页面
     */
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable Integer id, HttpServletRequest req) {
        ArticleEditVo articleEditVo = this.contentArticleService.findArticleById(id);
        if (articleEditVo != null) {
            List<Recomend> recomends = this.recomendService.findAll();
            Integer categoryId = articleEditVo.getCategoryId();
            List<Sort> sorts = this.sortService.findByCategoryId(categoryId);
            Set<Tag> tags = this.tagService.findByContentId(id);

            if (CollectionUtils.isNotEmpty(tags)) {
                StringBuffer tagStringBuff = new StringBuffer();
                String tagStr = "";
                if ((tags != null) && !tags.isEmpty()) {
                    for (Tag tag : tags) {
                        tagStringBuff.append(tag.getName()).append(",");
                    }
                    if (tagStringBuff.length() > 1) {
                        tagStr = tagStringBuff.substring(0, tagStringBuff.length() - 1);
                    }
                }
                articleEditVo.setTagsString(tagStr);
            }

            Set<Integer> recomendIds = this.recomendService.findRecomendIdsByContentId(id);
            articleEditVo.setRecomendIds(recomendIds);

            req.setAttribute("editVo", articleEditVo);
            req.setAttribute("recomends", recomends);
            req.setAttribute("sorts", sorts);
            return "back/content/article/edit";
        } else {
            // TODO 如文章不存在, 跳到错误页面
            return "";
        }

    }

    /**
     * 编辑文章 业务
     * @param id 内容id
     * @param vo 编辑vo
     * @param result JSR校验结果
     * @return 页面
     */
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
    public String edit(@PathVariable Integer id, @Valid @ModelAttribute("editVo") ArticleEditVo editVo, BindingResult result, HttpServletRequest req,
            RedirectAttributes ra) {
        if (!result.hasErrors()) {
            this.contentArticleService.updateArticle(editVo);
            // 成功
            return UrlUtil.success(ra, "修改成功", this.urlUtil.urlRelativeToBack(req, "/content"));
        }
        // JSR校验失败
        else {
            ArticleEditVo articleEditVo = this.contentArticleService.findArticleById(id);

            Integer categoryId = articleEditVo.getCategoryId();
            Category category = this.categoryService.findOne(categoryId);
            List<Sort> sorts = this.sortService.findByCategoryId(categoryId);

            // 所有的推荐方式
            List<Recomend> recomends = this.recomendService.findAll();
            req.setAttribute("recomends", recomends);
            req.setAttribute("category", category);
            req.setAttribute("sorts", sorts);
            return "back/content/article/edit";
        }
    }
}
